#include "lm75ad.h"

// 获取温度
float lm75ad_get_temp(void)
{
    uint16_t temp_reg = 0;
    float temp = 0.0;
    uint8_t recv_buf[2] = {0};
    lm75ad_read_reg(LM75AD_ADDR, TEMP_REG, recv_buf);
    temp_reg = recv_buf[0];
    temp_reg = (temp_reg << 3) | (recv_buf[1] >> 5);
    if (temp_reg & (0x01 << 10))
    {
        temp_reg = temp_reg & ~(0x01 << 10);
        temp_reg -= 1;
        temp_reg = (~temp_reg) & 0x03ff;
        temp = temp_reg * (-0.125);
    }
    else
    {
        temp = temp_reg * 0.125;
    }
    return temp;
}
// 读寄存器值
void lm75ad_read_reg(uint8_t lm75ad_id, uint8_t reg, uint8_t *buf)
{
    /*写指针字节（温度寄存器）*/
    while (i2c_flag_get(I2C0, I2C_FLAG_I2CBSY))
        ;
    i2c_start_on_bus(I2C0);
    while (!i2c_flag_get(I2C0, I2C_FLAG_SBSEND))
        ;
    i2c_master_addressing(I2C0, lm75ad_id, I2C_TRANSMITTER);
    while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND))
        ;
    i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);
    while (!i2c_flag_get(I2C0, I2C_FLAG_TBE))
        ;
    i2c_data_transmit(I2C0, reg);
    while (!i2c_flag_get(I2C0, I2C_FLAG_TBE))
        ;
    i2c_stop_on_bus(I2C0);
    while (I2C_CTL0(I2C0) & 0x0200)
        ; // 若为1，则还在发送stop；为0，则发送stop完毕
    /*读温度寄存器*/
    i2c_ackpos_config(I2C0, I2C_ACKPOS_NEXT);
    while (i2c_flag_get(I2C0, I2C_FLAG_I2CBSY))
        ;
    i2c_start_on_bus(I2C0);
    while (!i2c_flag_get(I2C0, I2C_FLAG_SBSEND))
        ;
    i2c_master_addressing(I2C0, lm75ad_id, I2C_RECEIVER);
    while (!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND))
        ;
    i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);
    while (!i2c_flag_get(I2C0, I2C_FLAG_BTC))
        ;
    while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE))
        ;
    *buf = i2c_data_receive(I2C0);
    i2c_ack_config(I2C0, I2C_ACK_DISABLE);
    while (!i2c_flag_get(I2C0, I2C_FLAG_RBNE))
        ;
    *(buf + 1) = i2c_data_receive(I2C0);
    i2c_stop_on_bus(I2C0);
    while (I2C_CTL0(I2C0) & 0x0200)
        ;                                        // 若为1，则还在发送stop；为0，则发送stop完毕
}
